package co.recloud.ariadne.model.plan;

import java.util.Map;
import co.recloud.ariadne.model.logical.Column;
import co.recloud.ariadne.model.logical.Condition;
import co.recloud.ariadne.model.logical.Table;
import co.recloud.ariadne.model.logical.Transaction;
import co.recloud.ariadne.persistor.KeyValuePersistor;
import co.recloud.ariadne.persistor.KeyValuePersistorImpl;

public class HashLookup extends Operator {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4810007611741338599L;

	public HashLookup(Transaction transaction) {
		super(transaction);
		// TODO Auto-generated constructor stub
	}

	private Condition condition;

	/**
	 * @param condition the condition to set
	 */
	public void setCondition(Condition condition) {
		this.condition = condition;
	}

	/**
	 * @return the condition
	 */
	public Condition getCondition() {
		return condition;
	}

	public String toString() {
		return "HashLookup: " + condition + " on " + this.getTable().getAlias() + " to " + this.getChildren();
	}
	
	public void execute(String localhost, int port) {
		this.getChildren().get(0).execute(localhost, port);
		KeyValuePersistor kv = new KeyValuePersistorImpl(this.getTransaction());
		Table childTable = this.getChildren().get(0).getTable();
		String key = condition.getRightValue();
		Map<String, Object> columnMap = kv.getAllColumns(key, childTable);
		for(String columnString : columnMap.keySet()) {
			Column column = Column.parseColumn(columnString, childTable, this.getTableAliases());
			kv.setValue(key, new Column(this.getTable(), column.getTable().getAlias() + "." + column.getField()), (String) columnMap.get(columnString));
		}
		if(childTable.getName().startsWith("RS")) {
			kv.dropTable(childTable);
		}
	}
}
